<template>
	<view class="control">
		<view class="control_item" v-for="(item, index) in list" :key="index" @click="openMenu(item)">
			<view class="control_item_name">
				{{item.name}}
			</view>
			<rui-icons icon="more" color="#999"></rui-icons>
		</view>
	</view>

	<rui-popup ref="popup">
		<view class="popup_menu">
			<view class="popup_menu_item" v-for="(item, index) in popup_menu" :key="index" @click="change(item)">
				{{item.name}}
			</view>
		</view>
	</rui-popup>
</template>

<script setup>
	import {
		ref
	} from "vue"

	import {
		getFinger,
		delFinger,
		editFinger,
	} from "@/common/api.js"

	import {
		onLoad
	} from "@dcloudio/uni-app"

	import ble from "@/util/ble"
	import {
		createBuffer
	} from "@/util/common"

	import {
		productStore
	} from "@/store"

	let show = ref(false)
	let popup = ref(null)
	let list = ref([])
	let info = {}
	let user_product_id = ""
	let instruct = "";

	let product = productStore()

	let popup_menu = ref([{
			menu_id: 1,
			name: "删除指纹",
			type: "modal"
		},
		{
			menu_id: 2,
			name: "修改名称",
			type: "input"
		},
	])

	onLoad(opts => {
		user_product_id = product.getInfo.id;
		getList()
	})

	const getList = () => {
		getFinger({
			user_product_id
		}).then(res => {
			list.value = res.data.list;
			instruct = res.data.instruct;
		})
	}

	const openMenu = (e) => {
		info = e;
		popup.value.open();
	}
	const change = (e, index) => {
		popup.value.close();
		if (e.type == 'modal') {

			uni.showModal({
				title: '删除提示',
				content: `确定要删除《${info.name}》？`,
				success: function(res) {
					if (res.confirm) {
						let key = info.finger_key == 10 ? 'a' : info.finger_key
						ble.send(createBuffer(12, 1, key), () => {
							delFinger({
								id: info.id,
								type: 'one'
							}).then(res => {
								uni.showToast({
									title: "成功删除",
									icon: "success"
								})
								getList()

								let fingerprint = product.getFingerprint;
								product.setFingerprint(fingerprint -= 1)
							})
						})
					}
				}
			});
		}

		if (e.type == 'input') {
			uni.showModal({
				title: '修改提示',
				editable: true,
				placeholderText: "请输入指纹新名称",
				success: function(res) {
					if (res.confirm) {
						editFinger({
							id: info.id,
							name: res.content
						}).then(res => {
							uni.showToast({
								title: "修改成功",
								icon: "success"
							})
							getList()
						})
					}
				}
			});
		}
	}
</script>

<style lang="scss" scoped>
	.popup {
		&_menu {
			&_item {
				padding: 30rpx 0;
				border-bottom: 1rpx solid #f5f6f7;
				text-align: center;

				&:active {
					background: #f5f6f7;
				}

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}

	.control {
		margin-top: 50rpx;

		&_item {
			margin: 20rpx;
			background: #fff;
			padding: 40rpx;
			border-radius: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}
</style>